<?php

namespace app\model;

use think\Model;
use think\model\concern\SoftDelete;

class TestModel extends Model
{
    protected $name = 'test';
    protected $pk = '_id';
    protected $readonly = ['_id',];
    protected $schema = [
        'name' => 'string',
        'age' => 'int',
        'sex' => 'int',
        'create_time' => 'int',
        'update_time' => 'int',
        'delete_time' => 'int',
    ];
    use SoftDelete;

    protected string $deleteTime = 'delete_time';
    protected $defaultSoftDelete = 0;

    protected static array $defaultData = [
        'name' => '',
        'age' => -1,
        'sex' => -1,
        // 'create_time' => 0,
        // 'update_time' => 0,
        'delete_time' => 0,
    ];

    public static function onBeforeInsert($model): void
    {
        // 设置默认值
        foreach (self::$defaultData as $key => $value) {
            if (!isset($model[$key])) $model[$key] = $value;
        }
    }

    public static function onAfterRead($model): void
    {
        // 设置默认值；但是我觉得不应该这样，应该通过运维手段，在数据层面彻底解决问题
        foreach (self::$defaultData as $key => $value) {
            if (!isset($model[$key])) $model[$key] = $value;
        }
    }
}